package com.example.apicommon;

import java.util.*;
import java.util.stream.*;
enum Singleton8 {
    INSTANCE;

    public void getInstance() {

    }
}

/**
 * @author: CYL
 * @DATE: 2023/7/23
 * @TIME: 15:19
 **/
public class StreamStudy {
    public static final void flatStream() {
        /**
         * stream 的扁平化 操作 flatMap
         */
        String[] s = {"Hello", "World"};
        List<String[]> v1 = Arrays.stream(s)
                .map(word -> word.split(""))
                .collect(Collectors.toList());

        System.out.println(v1); // 输出2个string[]数组 [[Ljava.lang.String;@433c675d, [Ljava.lang.String;@3f91beef]

        List<String> v2 = Arrays.stream(s)
                .map(word -> word.split(""))
                .flatMap(Arrays::stream)
                .collect(Collectors.toList());
        System.out.println(v2); // [H, e, l, l, o, W, o, r, l, d]
    }
    public static void main(String[] args) {
        flatStream();

        // stream() − 为集合创建串行流。
        // parallelStream() − 为集合创建并行流。
        // filter 方法用于通过设置的条件过滤出元素
        List<String> v1 = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
        List<String> v2 = v1.parallelStream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
        v2.forEach(System.out::println);

        // map 方法用于映射每个元素到对应的结果
        List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
        List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
        squaresList.forEach(System.out::println);


        // limit 方法用于获取指定数量的流
        // sorted 方法用于对流进行排序
        // new Random().ints() 返回 IntStream
        new Random().ints().limit(10).sorted().forEach(System.out::println);

        // Collectors 归约操作 一堆
        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
        List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
        System.out.println("筛选列表: " + filtered);
        String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(","));
        System.out.println("合并字符串: " + mergedString);

        // count max min 等等
        long count = numbers.stream().count();
        Integer maxn = numbers.stream().max((o1, o2) -> o1 - o2).get();
        Integer mixn = numbers.stream().min((o1, o2) -> o1 - o2).get();
    }
}
